var WxParse = require('../../../../wxParse/wxParse.js');
var HtmlParser = require('../../../../utils/htmlParseUtil.js');
var app = getApp();
var that;
Page({
  data: {
    item: {}, //详情
    isCollect: false,//是否被收藏
    remind: "加载中",
    id: ''
  },

  onLoad: function (options) {
    that = this;
    that.setData({ remind: '加载中'});
    that.getContentById(options.id || '5c57fd4a6fb9a049e660b169');
  },
  onHide: function () {
    that.setData({ remind: '' });
  },

  getContentById: function(id) {
    wx.request({
      url: 'https://bukaa.cn/api-cms/juejin/detail/' + id,
      method: 'GET',
      success: function(res){
        if (res.data.status == 'ok'){
          that.setData({
            item: {
              title: res.data.data.title,
              content: res.data.data.detail.content,
              author: JSON.parse(res.data.data.user).username,
              avatar: JSON.parse(res.data.data.user).avatarLarge,
              bio: res.data.data.createdAt
            }
          });
          WxParse.wxParse('main', 'html', dealCodeTag(res.data.data.detail.content), that, 5);
          that.setData({ remind: '' });
        }else{
          that.setData({ remind: '404' });
        }
      },
      error: function(){
        that.setData({ remind: '404' });
      }
    })
  },

  getContent: function (url) {
    wx.request({
      url: url,
      method: 'GET',
      success: function(res){
        console.log(res);
        if (res.statusCode == 200){
          var html = res.data;
          WxParse.wxParse('main', 'html', dealCodeTag(getArticleHtml(getMainHtml(html, "main"), "article")), that, 5);
          that.setData({ remind: '' });
        }else{
          that.setData({ remind: '404' });
        }
      }
    })
  },
  previewImgEvent: function (e) {
    var src = e.currentTarget.dataset.src;
    if (src && src.length > 0) {
      wx.previewImage({
        urls: [src]
      });
    }
  },
});

function dealCodeTag(html){
  html = html.replace(/<pre><code/ig, "<pre><wxxxcode-style").replace(/<\/code><\/pre>/ig, "</wxxxcode-style></pre>");
  return html;
};

function getMainHtml(html, tag) {
  console.time("getMainHtml:");
  var startIndex = html.indexOf("<" + tag);
  if (startIndex == -1){
    startIndex = 0;
  }
  var endIndex = html.indexOf("</" + tag + ">");
  if(endIndex == -1){
    endIndex = html.length;
  }else{
    endIndex += (3 + tag.length);
  }
  console.timeEnd("getMainHtml:");
  return html.substring(startIndex, endIndex);
}

function getArticleHtml(html, tag) {
  console.time("getArticleHtml:");
  var startIndex = html.indexOf("<" + tag);
  if (startIndex == -1) {
    startIndex = 0;
  }
  var endIndex = html.lastIndexOf("</" + tag + ">");
  if (endIndex == -1) {
    endIndex = html.length;
  } else {
    endIndex += (3 + tag.length);
  }
  console.timeEnd("getArticleHtml:");
  return html.substring(startIndex, endIndex);
}